package mx.com.matersys.vacs.servlet;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import flexjson.JSONSerializer;

public class PuntosChart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PuntosChart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("X");
		doPost(request,  response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ejecutaServlet(request,response);
	}
	
	protected void ejecutaServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String id = request.getParameter("idPaciente");
		
		if (id != null ) {
        	StringBuffer sb = new StringBuffer("");
    		sb.append("#|"+new Date().getTime()); // se agrega el tiempo
    		sb.append("|"+id); // se agrega el identificador del paciente
    		sb.append("|19.383759"); // se agrega latitud
    		sb.append("|-99.173766"); // se agrega longitud
    		sb.append("|38.5"); // se agrega temperatura
    		sb.append("|1&2&3&4"); // se agregan los eventos
    		sb.append("|1.4");   //x
    		sb.append("|2.8");   //y
    		sb.append("|4.2");   //z
    		sb.append("|");
    		getPoints(sb);
    		sb.append("|");
    		FileOutputStream fos = new FileOutputStream("C:\\bin\\archivoGenerado.txt");
    		fos.write(sb.toString().getBytes(), 0, sb.toString().getBytes().length);
    		fos.close();
    		//response.getOutputStream().print(sb.toString());
    	//	response.sendRedirect(request.getContextPath()+"/registrolecturas/guardaMensaje?mensaje="+sb.toString());
    		return;
        
        }
	
	}
	
	
	
	public void getPoints(StringBuffer sb) {
        try {
            BufferedReader br;
            FileReader f = new FileReader("/opt/mgh001.art");
            br = new BufferedReader(f);
            String cadena = br.readLine();  
            int counter = 0;
            int tasaMuestreo=200; //200 Hz
            int tiempoMin =3;
            
            while (cadena != null) {
                sb.append("&"+Double.parseDouble(cadena));
                if (counter++ > tasaMuestreo*tiempoMin*30) break;
                cadena = br.readLine();
            }
        } catch (Exception ex) {
            System.out.println("Error " + ex.getMessage());
        }

    }
	
	
/*	
	private String[] getParameterValues(String params){
		
		String []arr =null;
		if(params !=null ){
			arr = params.split("&");
			
			int idPaciente=0;
			if(arr != null && arr.length==4){
				for (int i = 0; i < arr.length; i++) {
					arr[i]= arr[i]!=null? arr[i].substring(arr[i].indexOf('=')+1, arr[i].length()):null;
				}
				
				
			}
		}
		return arr;
		   
	}
	
	
	private void ejecutaServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		JSONSerializer aq=new JSONSerializer();
		PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
		
		List<Double>  list = getPoints();
		
		
		
		out.print(aq.exclude("*.class").serialize(list));
		//System.out.println(aq.exclude("*.class").serialize(list));
		out.flush();
		
	}
	class Inner {
		public Inner(double x){this.x=x;}
		private double x;

		public double getX() {
			return x;
		}

		public void setX(double x) {
			this.x = x;
		}
		
		
	}
	
	public List<Double> getPoints() {
		
		   List<Double>  list = new ArrayList<Double>();
           try {
               BufferedReader br;
               FileReader f =new FileReader("C:\\bin\\brazalete\\mgh001.art");
               br= new BufferedReader(f);
               String cadena=br.readLine();
           int counter=0;
       	
               while(cadena!=null){
            	   list.add(Double.parseDouble(cadena));
            	   if(counter>2000)
            		   break;
            	   cadena=br.readLine();
               
               }
            } catch (Exception ex){
              System.out.println("Error " + ex.getMessage());
           }
           return list;
	}
	*/
}
